package com.think.admin.oauth.redis;

import com.think.admin.cons.AdminCons;
import com.think.common.utils.SysUtils;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.Date;

/**
 * <p>
 * 自定义RedisTokenStore：
 * 1.实现token自动续签
 * </p>
 *
 * @author: xwj
 * @data: 2019-05-13
 */
public class CustomRedisTokenStore extends RedisTokenStore {

    public CustomRedisTokenStore(RedisConnectionFactory connectionFactory) {
        super(connectionFactory);
    }

    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        OAuth2Authentication result = readAuthentication(token.getValue());
        if (SysUtils.isNotEmpty(result)) {
            // 如果token没有失效，更新AccessToken过期时间
            DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;

            // 重新设置过期时间
            oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis()
                    + (AdminCons.Param.LOGIN_TIME_OUT * 1000L)));

            // 将重新设置过的过期时间重新存入redis, 此时会覆盖redis中原本的过期时间
            storeAccessToken(token, result);
        }
        return result;
    }
}
